package org.jetnuke.modules.pictures;

import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.VelocityContext;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.dao.DataAccessDriver;
import org.jetnuke.dao.PictureDAO;
import org.jetnuke.dao.PictureVoteDAO;
import org.jetnuke.entities.PictureVote;
import org.jetnuke.util.JetUtil;

public class Vote implements IAction {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(Vote.class);

	int pid;
	int score;

	public void setPid(int pid) {
		this.pid = pid;
	}

	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {
		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - start"); //$NON-NLS-1$
		}

		if (ui == null || ui.getID() < 2)
			return null;
		PictureDAO pd = DataAccessDriver.getInst().newPictureDAO();
		if (pd.retrieveByPK(pid).getUID() == ui.getID()) {
			vc.put("reason", vc.get("_VOTE_YOUR_PICTURE"));
			ActionForward returnActionForward = new ActionForward(info,
					"invalid_vote.vm");
			if (logger.isDebugEnabled()) {
				logger
						.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - end"); //$NON-NLS-1$
			}
			return returnActionForward;
		}

		PictureVoteDAO pvd = DataAccessDriver.getInst().newPictureVoteDAO();
		if (pvd.alreadyVoted(pid, ui.getID())) {
			vc.put("reason", vc.get("_ALREADY_VOTED"));
			ActionForward returnActionForward = new ActionForward(info,
					"invalid_vote.vm");
			if (logger.isDebugEnabled()) {
				logger
						.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - end"); //$NON-NLS-1$
			}
			return returnActionForward;
		}
		PictureVote pv = new PictureVote();
		pv.setVOTE(score);
		pv.setPID(pid);
		pv.setVOTE_AUTHOR(ui.getID());
		pvd.addNew(pv);
		pd.vote(pid, score);
		JetUtil.redirect(vc, response, request.getContextPath()
				+ "/do/pictures/showmedium?pid=" + pid);

		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - end"); //$NON-NLS-1$
		}
		return null;
	}

	public void setScore(int score) {
		this.score = score;
	}

}
